<?php
class Thumb{
	private $_source='';
	private $_thumb_width=0;
	private $_thumb_height=0;
	private $_width=0;
	private $_height=0;
	private $_cut=false;
	private $_target='';

	private $_type; // 图像类型
	private $_img;  // 缩略图资源

	private $_func; // 生成图片的方法

	/**缩略图指定大小{{{
	 * @param $source 要缩略的源文件
	 * @param $width 缩略图宽度
	 * @param $height 缩略图高度
	 * @param $cut 是否裁切
	 * @param $target 缩略图生成的位置
	 * 
	 */	
	public function resizeImg($source,$target,$width=100,$height=100,$cut=false){
		$this->_source = $source;
		$this->_thumb_width = $width;
		$this->_thumb_height = $height;

		$this->_target = $target;
		$this->_cut=$cut;

		$this->_type = strtolower(substr(strrchr($source,'.'),1));

		// 初始化对象
		$this->init();

		$this->_width = imagesx($this->_img);
		$this->_height = imagesy($this->_img);

		$this->general();
		imagedestroy($this->_img);
	}
	/*}}}*/

	private function init(){
		switch($this->_type){
			case  'png':
				$this->_img = imagecreatefrompng($this->_source);
				$this->_func = 'imagepng';
				break;
			case  'jpeg':
				$this->_img = imagecreatefromjpeg($this->_source);
				$this->_func = 'imagejpeg';
				break;
			case  'jpg':
				$this->_img = imagecreatefromjpeg($this->_source);
				$this->_func = 'imagejpeg';
				break;
			case  'gif':
				$this->_img = imagecreatefromgif($this->_source);
				$this->_func = 'imagegif';
				break;
		}
	}

	private function general(){
		// 改变后的图像比例
		$t_rate = $this->_thumb_width/$this->_thumb_height;

		$rate = $this->_width/$this->_height;
		if($this->_cut){ // 裁图
			if($rate >= $t_rate){ // 高度优先
				$newimg = imagecreatetruecolor($this->_thumb_width,$this->_thumb_height);
				imagecopyresampled($newimg,$this->_img,0,0,0,0,$this->_thumb_width,$this->_thumb_height,(($this->_height)*$t_rate),$this->_height);
			}else{
				$newimg = imagecreatetruecolor($this->_thumb_width,$this->_thumb_height);
				imagecopyresampled($newimg,$this->_img,0,0,0,0,$this->_thumb_width,$this->_thumb_height,$this->_width,(($this->_width)/$t_rate));
			}
		}else{ // 不裁图
			if($rate >= $t_rate){ // 高度优先
				$newimg = imagecreatetruecolor($this->_thumb_width,$this->_thumb_width/$rate);
				imagecopyresampled($newimg,$this->_img,0,0,0,0,$this->_thumb_width,$this->_thumb_width/$rate,$this->_width,$this->_height);
			}else{
				$newimg = imagecreatetruecolor($this->_thumb_height*$rate,$this->_thumb_height);
				imagecopyresampled($newimg,$this->_img,0,0,0,0,$this->_thumb_height*$rate,$this->_thumb_height,$this->_width,$this->_height);
			}
		}

		call_user_func_array($this->_func,array($newimg,$this->_target));
	}
}
